<template>
  <div id="baidu-map-container"></div>
</template>

<script>
import axios from 'axios'
import {  getHouseLocations, getDeviceLocations } from "@/api/screen/index";
export default {
  name: 'BaiduMap',
  props: {
    center: { type: Object, default: () => ({ lng: 118.7969, lat: 32.0603 }) }, // 南京坐标
    zoom: { type: Number, default: 10 },
    mapStyleId: { type: String, default: '292b3b274c4924d87a3289128afda711' }
  },
  data() {
    return {
      map: null,
      markerIcons: {
        house: require('@/assets/logo/logo.png'),
        device: require('@/assets/images/device_marker.png')
      }
    };
  },
  mounted() {
    this.initMap();
    this.loadGeoJsonData();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy(); // 清理地图实例
    }
  },
  methods: {
    async loadGeoJsonData() {
      try {
        const response = await axios.get(
          'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=320100_full'
        );
        this.geoJsonData = response.data;
        this.addOverlay();
      } catch (error) {
        console.error('Failed to load GeoJSON data:', error);
      }
    },
    addOverlay() {
      if (!this.geoJsonData) return;

      // 解析 GeoJSON 数据
      const features = this.geoJsonData.features;
      features.forEach(feature => {
        const geometry = feature.geometry;
        if (geometry.type === 'Polygon') {
          const paths = geometry.coordinates[0].map(coord => new BMapGL.Point(coord[0], coord[1]));
          this.drawPolygon(paths);
        } else if (geometry.type === 'MultiPolygon') {
          geometry.coordinates.forEach(polygon => {
            const paths = polygon[0].map(coord => new BMapGL.Point(coord[0], coord[1]));
            this.drawPolygon(paths);
          });
        }
      });
    },
    drawPolygon(paths) {
      const polygon = new BMapGL.Polygon(paths, {
        strokeColor: '#83F3FE ', // 蓝色边框
        strokeWeight: 2,        // 边框宽度
        fillColor: '#005cc7',   // 蓝色填充
        fillOpacity: 0.8        // 透明度
      });
      this.map.addOverlay(polygon);
    },
    initMap() {
      this.$nextTick(async () => {
        this.map = new BMapGL.Map('baidu-map-container', { enableMapClick: false });
        this.map.centerAndZoom(new BMapGL.Point(this.center.lng, this.center.lat), this.zoom);
        this.map.enableScrollWheelZoom(true); // 允许滚轮缩放
        this.map.setHeading(75);
        // 设置个性化地图样式
        this.setMapStyle(this.mapStyleId);
        const [houseRes, deviceRes] = await Promise.all([
          getHouseLocations(),
          getDeviceLocations()
        ]);
        // 添加控件
        //const scaleCtrl = new BMapGL.ScaleControl();  // 比例尺
        //this.map.addControl(scaleCtrl);
        //addPolygon()
        // 添加标记
        if (houseRes.code === 200) {
          houseRes.data.map((item)=>{
          this.addMarker(item,'house')
        })
        }
        if (deviceRes.code === 200) {
          deviceRes.data.map((item)=>{
          this.addMarker(item,'device')
        })
        }
       
      });
    },
    // 在 initMap 方法中添加
    addPolygon() {
      const boundaryPoints = [
        new BMapGL.Point(118.5, 32.2),
        new BMapGL.Point(118.8, 32.1),
        new BMapGL.Point(119.0, 32.3),
        // ... 替换为实际南京边界坐标（需转换坐标系）
      ];

      const polygon = new BMapGL.Polygon(boundaryPoints, {
        strokeColor: "#FF0000",
        strokeWeight: 2,
        fillColor: "#FF4500",
        fillOpacity: 0.2
      });
      this.map.addOverlay(polygon);
      // 创建去除文字的地图样式
      // var mapStyle = {
      //       styleJson: [
      //           {
      //               "featureType": "all",
      //               "elementType": "labels.text",
      //               "stylers": {
      //                   "visibility": "off"
      //               }
      //           }
      //       ]
      //   };
      //   var customMapType = new BMapGL.MapType('无文字地图', mapStyle);
      //   this.map.addMapType(customMapType);
      //   function updateMapType() {
      //       var pixels = this.map.getSize();
      //       for (var x = 0; x < pixels.width; x++) {
      //           for (var y = 0; y < pixels.height; y++) {
      //               var point = this.map.pixelToPoint(new BMapGL.Pixel(x, y));
      //               if (BMapGL.Util.isPointInPolygon(point, polygon)) {
      //                   // 框选区域内使用默认地图类型
      //                   this.map.setMapType(BMAP_NORMAL_MAP);
      //               } else {
      //                   // 框选区域外使用无文字地图类型
      //                   this.map.setMapType(customMapType);
      //               }
      //           }
      //       }
      //   }

        // 初始更新地图类型
        updateMapType();
    },
    setMapStyle(styleId) {
      this.map.setMapStyleV2({
        styleId: styleId // 设置个性化样式 ID
      });
    },
    addMarker(val,type) {
      var icon = new BMapGL.Icon(type=='house'?this.markerIcons.house:this.markerIcons.device, new BMapGL.Size(16, 16));
      const marker = new BMapGL.Marker(new BMapGL.Point(val.longitude, val.latitude),{ icon: icon });
      this.map.addOverlay(marker);

      // // 添加信息窗口
      // const infoWindow = new BMapGL.InfoWindow("南京市");
      // marker.addEventListener('click', () => {
      //   this.map.openInfoWindow(infoWindow, marker.getPosition());
      // });
    }
  }
};
</script>

<style scoped>
#baidu-map-container {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;

  left: 0;
  margin: auto;
  width: 100%;
  height: 100%;
  border-radius: 5%;
  z-index: 0
}
</style>